package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional//加入SQL的事务管理 一起成功||一起失败
    public void saveWithFlavor(DishDto dishDto) {
        //多态父类引用指向子类实现类对象,如此调用只会调用父类中定义的内容不会调用出子类的独有内容
        Dish dish = dishDto;
        //this.save就是本类调用save方法
        this.save(dish);
        //第二种写法
        //this.save(dishDto)
        //此写法 因save方法需要的是dish对象数据传入dishDto也是父类引用指向子类实现类对象
        //不过是在一瞬间完成的
        Long dishdId = dishDto.getId();
        //获取到id信息(菜品id)
        //获取到口味信息封装到一个集合中
        List<DishFlavor> flavors = dishDto.getFlavors();
        if (flavors != null && flavors.size() > 0)
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishdId);
            }
        //批量存储
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto showById(Long id) {
        DishDto dishDto = new DishDto();
        //根据id查询菜品基础信息存入dishDto中
        Dish dish = this.getById(id);
        //把dish中的内容赋值到dishDto中
        BeanUtils.copyProperties(dish, dishDto);
        //根据id查出菜品对应的口味信息也存入dishDto中一并返回
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, id);
        //对比id并查询口味关系
        List<DishFlavor> list = dishFlavorService.list(wrapper);
        dishDto.setFlavors(list);
        //进行回显
        return dishDto;

    }

    @Override
    public void upDateWithFlavor(DishDto dishDto) {
        //重写菜品数据
        this.updateById(dishDto);
        //清除菜品口味
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        //获取到当前菜品响应的id对应的口味列表
        wrapper.eq(DishFlavor::getDishId, dishDto.getId());
        //删除操作
        dishFlavorService.remove(wrapper);
        //获取到口味信息封装到一个集合中
        List<DishFlavor> flavors = dishDto.getFlavors();
        if (flavors != null && flavors.size() > 0)
            for (DishFlavor flavor : flavors) {
                //获取口味对应的菜品id
                flavor.setDishId(dishDto.getId());
            }
        //批量存储
        dishFlavorService.saveBatch(flavors);
    }
}
